package network;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class EchoThread extends Thread {
	
	private Socket sock;
	
	public EchoThread(Socket sock) {
		this.sock = sock;
	}
	
	@Override
	public void run() {
		try {
			InputStream in = sock.getInputStream();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			
			OutputStream out = sock.getOutputStream();
			BufferedWriter writer = new BufferedWriter(
					new OutputStreamWriter(out));
			
			String dataFromClient = null;
			while ((dataFromClient = reader.readLine()) != null) {
				System.out.println(sock.getInetAddress() + ": "
						+ dataFromClient);
				writer.write(dataFromClient + "\n");
				writer.flush();
			}
		} catch (IOException e) {
//			e.printStackTrace();
		} finally {
			try {
				sock.close();
			} catch (IOException e) {}
			System.out.println("클라이언트와의 연결이 끊겼습니다. "
					+ sock.getInetAddress());
		}
	}
	
}
